const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;
const utils           = require('../../../utils');

class SignupHandler extends BaseHandler {

    get pattern() {
        return "/signup";
    }

    doGET(request, response) {
        var session = request.session;
        if(session && session.user && session.user.authenticated) {
            response.redirect('/console');
            return;
        }
        var security_code = utils.uuid();
        request.session.user.security_code = security_code;
        this.ensureRef(request);
        var host = request.headers['host'];
        var logo = '/dashboard/images/sign-in-logo.png';
        if (['localhost:3000', 'onwall-ppe.parllay.cn', 'billboards.parllay.cn'].indexOf(host) < 0) {
            logo = `/oem/${host}/images/login-logo.png`;
        }
        response.render('console/login', {
            success: true,
            is_login: false,
            security_code: security_code,
            data: {},
            logo: logo
        });
    }

    doPOST(request, response) {
        var me = this;
        var security_code = utils.uuid();
        var host = request.headers['host'];
        var logo = '/dashboard/images/sign-in-logo.png';
        if (['localhost:3000', 'onwall-ppe.parllay.cn', 'billboards.parllay.cn'].indexOf(host) < 0) {
            logo = `/oem/${host}/images/login-logo.png`;
        }
        if(!request.body.security_code || request.body.security_code !== request.session.user.security_code) {
            request.session.user.security_code = security_code;
            response.render('console/login', {
                success: false,
                is_login: false,
                error: request.t('login.errors.invalid_request'),
                security_code : security_code,
                logo: logo,
                data: request.body
            });
            return;
        }
        var data = request.body;
        var name = (data.name || '').trim();
        var email = (data.email || '').trim();
        var password = (data.password || '').trim();
        var pageData = {
            is_login: false,
            data: data
        };
        pageData.security_code = security_code;
        request.session.user.security_code = security_code;
        var can_continue = true;
        if(!name || !email || !password) {
            can_continue = false;
            pageData.error = request.t('login.errors.user_or_email_or_password_empty');
        }
        
        if(can_continue && password.length < 6) {
            can_continue = false;
            pageData.error = request.t('login.errors.invalid_password_len');
        }
        
        if(can_continue && !utils.verifyEmailAddress(email)) {
            can_continue = false;
            pageData.error = request.t('login.errors.invalid_email_address');
        }
        pageData.success = can_continue;
        pageData.logo = logo;
        if(can_continue) {
            //TODO: Use system configuration instead
            let selfServiceUserId = 2001;
            let internalOrderId = 1000;
            let initialPlanId = 1000;
            let locale = request.locale;
            this.Controller.saveOrUpdateSystemUser(selfServiceUserId, internalOrderId, initialPlanId, name, email, password, request.session.user.refs, locale, null, (result) => {
                if(!result.success) {
                    pageData.success = false;
                    pageData.error = result.error;
                    response.render('console/login', pageData);
                } else {
                    delete request.session.user.security_code;
                    request.session.user.authenticated = true;
                    request.session.user.id = result.data.id;
                    request.session.user.name = result.data.name;
                    request.session.user.hash_id = result.data.hash_id;
                    request.session.user.profile_image = me.Controller.getCDNImageURL(result.data.profile_image);
                    request.session.user.ref = result.data.ref;
                    request.session.user.qr_code = result.data.qr_code;
                    response.redirect('/console');
                }
            });
        } else {
            response.render('console/login', pageData);
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
        this.registerVerb(HTTP_VERBS.POST, this.doPOST);
    }
}

module.exports = SignupHandler